/*
 * @Author: lin_zizhuo 2297304135@qq.com
 * @Date: 2023-11-20 07:34:22
 * @LastEditors: lin_zizhuo 2297304135@qq.com
 * @LastEditTime: 2023-11-20 17:08:05
 * @FilePath: /cpp_-linux/named_pipe/serve.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

#include "comm.hpp"
#include "log.hpp"

// 统一在服务器端接收信息，在服务器端发送信息
// 并且管道文件的销毁和生成将会在服务器端执行

int main()
{
    // debug ..
    // Log log;
    // log.change_record_op(one_file);
    // log.send_message(Warning, "nihao:%s", "hello");
    // log.send_message(Fatal, "fatal:%s", "hello");
    // log.send_message(Debug, "debug:%s", "hello");
    // log.send_message(Info, "info:%s", "hello");
    // log.send_message(Error, "error:%s", "hello");

    // 利用构造函数和析构函数解决了创建管道文件需要自己关闭的问题
    Init init;
    Log log;
    // 打开管道文件
    int fd = open(fifo_name, O_RDONLY);
    if (fd == -1)
    {
        log.send_message(Fatal, "open fifo error!\n");
        // perror("open fifo");
        exit(FIFO_OPEN_ERR);
    }
    log.send_message(Info, "serve open fifo_file excuess!\n");
    // 进行通信
    while (true)
    {
        char buffer[buffer_size];
        ssize_t num = read(fd, buffer, buffer_size);
        if (num > 0)
        {
            buffer[num] = 0;
            cout << "server get a mesg:" << buffer << endl;
        }
        else if (num == 0)
        {
            log.send_message(Info, "server quit\n");
            break;
        }
        else
        {
            log.send_message(Fatal, "read error!\n");
            exit(FIFO_READ_ERR);
        }

        // 删除管道文件
        // 操作利用析构函数执
    }
    return 0;
}